package com.thermal.thermal_inspection.aspect;

import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Aspect
@Component
public class AuthAspect {

    // 拦截所有带有 @RequireAdmin 注解的方法
    @Around("@annotation(com.thermal.thermal_inspection.annotation.RequireAdmin)")
    public Object checkAdminPermission(ProceedingJoinPoint joinPoint) throws Throwable {
        // 1. 获取当前请求（从请求头或Token中解析用户角色）
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userRole = request.getHeader("X-User-Role"); // 假设角色通过请求头传递

        // 2. 验证角色
        if (!"admin".equals(userRole)) {
            throw new RuntimeException("无权访问：需要管理员权限"); // 或返回自定义错误码
        }

        // 3. 放行请求
        return joinPoint.proceed();
    }
}
